package com.cleargroup.magic.cleara

import android.Manifest
import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.ResolveInfo
import android.os.Bundle
import android.provider.Settings
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.aa.base.BaseActivity
import com.aa.base.BaseUtils
import com.aa.base.log.AppsFlyerUtils
import com.aa.base.log.TAUtils
import com.aa.base.startAActivity
import com.aa.base.toast
import com.helpudashi.ccniu.R
import com.cleargroup.magic.cleara.c.BatteryHelper
import com.helpudashi.ccniu.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class MainActivity : BaseActivity<ActivityMainBinding>() {
    override fun initBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }
    var wavePercent = 0
    var waveValueAnimator: ValueAnimator? = null

    var needCleanSize = 0L
    override fun initLogic(savedInstanceState: Bundle?) {

        binding.featureCleanBattery.setOnClickListener {
            val powerUsageIntent = Intent(Intent.ACTION_POWER_USAGE_SUMMARY)
            val resolveInfo: ResolveInfo? = packageManager.resolveActivity(powerUsageIntent, 0)
            if (resolveInfo != null) {
                startActivity(powerUsageIntent)
            } else {
                "您的手机不支持该功能".toast()
            }
        }
        binding.featureCleanWindow.setOnClickListener {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                startActivity(
                    Intent(
                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION
                    )
                )
            } else {
                "您的手机不支持该功能".toast()
            }

        }
        binding.featureCleanWallpaper.setOnClickListener {
            val intent = Intent(Settings.ACTION_APPLICATION_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
            startActivity(intent);

        }

        binding.setting.setOnClickListener {
            startAActivity(SettingActivity::class.java)
        }

        setCleanFunction()

        setProtectNumber()
    }

    private fun setProtectNumber() {
        val firstInstallTime = BaseUtils.getFirstInstallTime(this)
        val lastCld = Calendar.getInstance()
        lastCld.timeInMillis = firstInstallTime
        lastCld.set(Calendar.HOUR_OF_DAY, 0)
        lastCld.set(Calendar.MINUTE, 0)
        lastCld.set(Calendar.SECOND, 0)
        lastCld.set(Calendar.MILLISECOND, 0)
        val lastZero = lastCld.timeInMillis

        val now = System.currentTimeMillis()
        val d = (now - lastZero) / 86400000 + 1
        val fCp2 =
            ForegroundColorSpan(ContextCompat.getColor(this, R.color.privacy_file_name_color))
        val toString = d.toString()
        val protectNumber = SpannableString(toString)
        protectNumber.setSpan(fCp2, 0, toString.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

        val contextStrBuilder =
            SpannableStringBuilder()
                .append(getString(R.string.app_name))
                .append("保护您的第")
                .append(protectNumber)
                .append("天")
        binding.tip.text = contextStrBuilder
    }

    fun setCleanFunction() {
        binding.apply {

            featureCleanOneClickAcceleration.setOnClickListener {
                checkPermissionAndOpenActivity(
                    R.string.rest_clean_permission_info,
                    "clean1"
                ) {
                    FeatureCleanLottieActivity.start(getActivity(), 1)
                }
            }

            featureCleanCpuCool.setOnClickListener {
                checkPermissionAndOpenActivity(
                    R.string.rest_clean_permission_info,
                    "clean2"
                ) {
                    FeatureCleanLottieActivity.start(getActivity(), 2)
                }
            }

            wavePercent = WaveSp.lastNumber
            if (wavePercent < 30 || (kotlin.math.abs(WaveSp.lastRandomTime - System.currentTimeMillis()) > 10 * 60 * 1000)) {
                wavePercent = (30..80).random()
                WaveSp.lastNumber = wavePercent
                WaveSp.lastRandomTime = System.currentTimeMillis()
            }
            if (kotlin.math.abs(WaveSp.lastCleanTime - System.currentTimeMillis()) > 20 * 60 * 1000) {
                // nothing
            } else {
                wavePercent = 100
                featureCleanRestCleanTv.text = "再次清理"
                setHomeCleanComplete()
            }

            featureCleanRestClean.setOnClickListener {
                // 打开放心清理
                if (wavePercent == 100) {
                    checkPermissionAndOpenActivity(
                        R.string.rest_clean_permission_info,
                        "clean3"
                    ) {
                        FeatureCleanLottieActivity.start(getActivity(), 3)
                    }
                } else {
                    cacheSizeContainer.callOnClick()
                }
            }
            cacheSizeContainer.setOnClickListener {
                if (fingerGuide.visibility != View.VISIBLE) {

                }else if (wavePercent == 100) {
                    featureCleanRestClean.performClick()
                } else {
                    AppsFlyerUtils.trackFunctionUse(getActivity())
                    lifecycleScope.launch(Dispatchers.IO) {
                        BatteryHelper.clearCache()
                    }
                    checkPermissionAndOpenActivity(
                        R.string.rest_clean_permission_info,
                        "clean0"
                    ) {
                        FeatureCleanLottieActivity.start(getActivity(), 0, needCleanSize)
                    }
                    needCleanSize = 0L
                    if (waveValueAnimator == null || !waveValueAnimator!!.isRunning) {
                        waveValueAnimator = ValueAnimator.ofInt(wavePercent, 100)
                        waveValueAnimator!!.addUpdateListener {
                            try {
                                val av = it.animatedValue
                                if (av is Int) {
                                    wavePercent = av
                                    if (av >= 100) {
                                        WaveSp.lastCleanTime = System.currentTimeMillis()
                                        WaveSp.lastNumber = 0
                                        setHomeCleanComplete()
                                    }
                                }
                            } catch (e: Exception) {
                            }
                        }
                        waveValueAnimator!!.setDuration(5000L).start()
                    }
                }

                TAUtils.trackClickEvent("optimize_now", "clean")
            }
            topLottie.post {
                lifecycleScope.launchWhenResumed {


                    withContext(Dispatchers.IO) {

                        if (wavePercent < 100) {
                            BatteryHelper.scanGarbage(
                                getActivity(),
                                null
                            ) { isEnd, path, size ->
                                lifecycleScope.launch(Dispatchers.Main) {

                                    if (isEnd) {
                                        cacheScanDesc.text = "立即优化"
                                        fingerGuide.visibility = View.VISIBLE
                                        fingerGuide.playAnimation()
                                        var size1 = size
                                        if (size1 <= 0) {
                                            size1 = (1000..5000).random().toLong()
                                        }
                                        val size2 = size1 * (5..30).random()
                                        needCleanSize = size2
                                        cacheSizeTv.text =
                                            BatteryHelper.formatSizeForJunkHeader(size2)
                                        featureCleanRestCleanTv.text = "放心清理"
                                    } else {
                                        cacheScanDesc.text = path
                                        cacheSizeTv.text =
                                            BatteryHelper.formatSizeForJunkHeader(size)
                                    }
                                }
                            }
                        } else {
                            lifecycleScope.launch(Dispatchers.Main) {
                                fingerGuide.visibility = View.VISIBLE
                                fingerGuide.playAnimation()
                            }
                        }
                    }

                }
            }
        }
    }


    var lastPermissionRequestTime = 0L
    fun checkPermissionAndOpenActivity(

        message: Int,
        tag: String,
        f: () -> Unit
    ) {
            if (checkPermission(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE))) {
                f.invoke()
            } else {
                AlertDialog.Builder(this)
                    .setMessage(getString(message))
                    .setPositiveButton(
                        ("确定")
                    ) { _, _ ->
                        lastPermissionRequestTime = System.currentTimeMillis()
                        askPermission(
                            arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ),
                            kotlin.math.abs(tag.hashCode())
                        ) {
                            f.invoke()
                        }
                    }.setNegativeButton("取消") { _, _ ->

                    }.show()
            }
    }

    private fun setHomeCleanComplete() {
        binding.cacheSizeTv.text = "0B"
        binding.cacheScanDesc.text = "点击再次清理"
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (checkPermissionFileRead()) {
            when (requestCode) {
                kotlin.math.abs("clean0".hashCode()) -> {
                    FeatureCleanLottieActivity.start(getActivity(), 0, needCleanSize)
                }
                kotlin.math.abs("clean1".hashCode()) -> {
                    FeatureCleanLottieActivity.start(getActivity(), 1)
                }
                kotlin.math.abs("clean2".hashCode()) -> {
                    FeatureCleanLottieActivity.start(getActivity(), 2)
                }
                kotlin.math.abs("clean3".hashCode()) -> {
                    FeatureCleanLottieActivity.start(getActivity(), 3)
                }
            }
        }
    }

}